import oss2
import re
from app.utils.timetool import time_now
from app.utils.token import make_uuid
import random


class UploadOssPath:
    access_key = None
    access_value = None
    endpoint = None

    def link_bucket(self, path_name):
        self.auth = oss2.Auth(self.access_key, self.access_value)
        return oss2.Bucket(self.auth, self.endpoint, path_name)


class LinkUploadOss:
    """
        上传阿里云oss
    """

    def __init__(self, oss_path='name', path_name='thisvadio'):
        self.bucket = up_oss_path.link_bucket(path_name)
        self.oss_path = oss_path

    def upload_some_oss(self, put_result, current_file_path):
        """
        传输数据是否成功,并且返回数据链接
        :param put_result: 上传数据返回结果
        :param current_file_path: 上传路径
        :return: 200 数据链接
                 other False
        """
        if put_result.status == 200:
            return f"""https://{self.oss_path}.{re.findall('http://(.*)', self.bucket.endpoint)[0]}/{current_file_path}"""  # 公司的oss
        else:
            return False

    def type_name(self, file_path, oss_path, name, type_name):
        """
        :param file_path: 所传文件路径
        :param oss_path: oss储存文件
        :param name: 自定义文件名字
        :param type_name: 文件名字状态 num->随机数,time->当前时间,uuid->uuid随机,路径文件原名
        :return: 传输后oss路径
        """
        file_suffix = str(file_path).split('.')[-1]
        if name:
            name = f"""{name}.{file_suffix}"""
        else:
            if type_name == 'num':
                name = f"""{str(random.randint(0, 999999999))}.{file_suffix}"""
            elif type_name == 'time':
                name = f"""{str(time_now())}.{file_suffix}"""
            elif type_name == 'uuid':
                name = f"""{make_uuid()}.{file_suffix}"""
            else:
                name = file_path.replace('\\', ' ').replace('/', ' ').split(' ')[-1]
        return f"""{oss_path}/{name}"""

    def upload_oss_from_file(self, file_path, name=None, type_name=None):
        """
        :param file_path: 所传文件路径
        :param oss_path: oss储存文件
        :param name: 自定义文件名字
        :param type_name: 文件名字状态 num->随机数,time->当前时间,uuid->uuid随机,路径文件原名
        :return: 传输后oss路径
        """
        current_file_path = self.type_name(file_path, self.oss_path, name, type_name)
        # 上传
        put_result = self.bucket.put_object_from_file(current_file_path, file_path,
                                                      headers={'Content-Disposition': 'inline'})
        return self.upload_some_oss(put_result, current_file_path)


up_oss_path = UploadOssPath()
# 链接oss数据
up_oss_path.access_key = 'LTAI5tB86NWrtJPMopyXJv8v'
up_oss_path.access_value = 'efyGN6WOn1zkkJcbbSttu6qJlcVi35'
up_oss_path.endpoint = 'http://oss-cn-beijing.aliyuncs.com'
a = 'http://oss-cn-beijing.aliyuncs.com'
